import { ref, reactive, computed } from 'vue';
import { defineStore } from 'pinia';
import type { HttpTransaction } from '../types';
import { apiClient } from '../api/client';
import { wsClient } from '../api/websocket';
import { transactionDB } from '../utils/indexedDB';

export const useTransactionsStore = defineStore('transactions', () => {
  // 状态
  const transactions = ref<HttpTransaction[]>([]);
  const selectedTransaction = ref<HttpTransaction | null>(null);
  const loading = ref(false);
  const error = ref<string | null>(null);
  
  // WebSocket连接状态
  const wsConnected = ref(false);
  const wsReconnecting = ref(false);
  const wsReconnectAttempts = ref(0);
  
  // IndexedDB 状态
  const dbInitialized = ref(false);
  
  // 分页信息
  const pagination = reactive({
    page: 1,
    pageSize: 100,
    total: 0
  });

  // 过滤条件
  const filters = reactive({
    search: '',
    method: '',
    statusCode: '',
    dateRange: null as [number, number] | null
  });

  // 初始化 IndexedDB
  async function initDatabase() {
    try {
      await transactionDB.init();
      dbInitialized.value = true;
      console.log('IndexedDB 初始化成功');
    } catch (error) {
      console.error('IndexedDB 初始化失败:', error);
    }
  }

  // 从 IndexedDB 加载历史记录
  async function loadFromIndexedDB() {
    if (!dbInitialized.value) {
      await initDatabase();
    }

    try {
      loading.value = true;
      const cachedTransactions = await transactionDB.getLatestTransactions(100);
      
      if (cachedTransactions.length > 0) {
        transactions.value = cachedTransactions;
        pagination.total = cachedTransactions.length;
        console.log(`从 IndexedDB 加载了 ${cachedTransactions.length} 条历史记录`);
      }
    } catch (error) {
      console.error('从 IndexedDB 加载数据失败:', error);
    } finally {
      loading.value = false;
    }
  }

  // 保存交易记录到 IndexedDB
  async function saveToIndexedDB(transaction: HttpTransaction) {
    if (!dbInitialized.value) {
      await initDatabase();
    }

    try {
      await transactionDB.addTransaction(transaction);
      // 定期清理，只保留最新的 1000 条记录
      const count = await transactionDB.getTransactionCount();
      if (count > 1000) {
        await transactionDB.keepLatestTransactions(1000);
      }
    } catch (error) {
      console.error('保存到 IndexedDB 失败:', error);
    }
  }

  // 获取交易记录列表（保留原有接口，但主要用于初始化）
  async function fetchTransactions(refresh = false) {
    if (refresh) {
      // 如果是刷新操作，清空当前数据
      transactions.value = [];
      selectedTransaction.value = null;
      pagination.page = 1;
      pagination.total = 0;
    }

    // 首先尝试从 IndexedDB 加载
    await loadFromIndexedDB();
  }

  // 获取单个交易记录详情
  async function fetchTransactionDetail(id: string) {
    try {
      const response = await apiClient.getTransaction(id);
      const transaction = response.data;
      
      // 更新列表中的记录
      const index = transactions.value.findIndex(t => t.id === id);
      if (index >= 0) {
        transactions.value[index] = transaction;
      }
      
      // 如果是当前选中的记录，更新选中状态
      if (selectedTransaction.value?.id === id) {
        selectedTransaction.value = transaction;
      }
      
      return transaction;
    } catch (err) {
      console.error('获取交易详情失败:', err);
      throw err;
    }
  }

  // 选择交易记录
  function selectTransaction(transaction: HttpTransaction | null) {
    selectedTransaction.value = transaction;
  }

  // 添加新的交易记录（WebSocket推送）
  function addTransaction(transaction: HttpTransaction) {
    // 检查是否已存在
    const existingIndex = transactions.value.findIndex(t => t.id === transaction.id);
    
    if (existingIndex >= 0) {
      // 更新现有记录
      transactions.value[existingIndex] = transaction;
    } else {
      // 添加到列表开头
      transactions.value.unshift(transaction);
      pagination.total++;
    }

    // 保持列表大小限制（前端显示限制）
    if (transactions.value.length > 1000) {
      transactions.value = transactions.value.slice(0, 1000);
    }

    // 异步保存到 IndexedDB
    saveToIndexedDB(transaction);
  }

  // 更新交易记录（WebSocket推送）
  function updateTransaction(transaction: HttpTransaction) {
    const index = transactions.value.findIndex(t => t.id === transaction.id);
    if (index >= 0) {
      transactions.value[index] = transaction;
      
      // 如果是当前选中的记录，更新选中状态
      if (selectedTransaction.value?.id === transaction.id) {
        selectedTransaction.value = transaction;
      }

      // 异步更新 IndexedDB
      saveToIndexedDB(transaction);
    }
  }

  // 清空交易记录
  async function clearTransactions() {
    // 首先尝试清空服务端数据库
    let serverCleared = false;
    try {
      console.log('🔄 尝试清空服务端数据库...');
      const response = await apiClient.clearAllRecords();
      if (response.data?.success) {
        console.log('✅ 服务端数据库已清空');
        serverCleared = true;
      }
    } catch (error) {
      console.warn('⚠️ 清空服务端数据库失败，可能服务器未连接:', error instanceof Error ? error.message : String(error));
    }

    // 清空前端数据
    transactions.value = [];
    selectedTransaction.value = null;
    pagination.page = 1;
    pagination.total = 0;

    // 清空 IndexedDB
    try {
      await transactionDB.clearAllTransactions();
      console.log('✅ 已清空 IndexedDB 中的所有记录');
    } catch (error) {
      console.error('❌ 清空 IndexedDB 失败:', error);
    }

    // 返回清空状态
    return {
      localCleared: true,
      serverCleared: serverCleared
    };
  }

  // 应用过滤条件
  function applyFilters() {
    // 重新获取数据
    pagination.page = 1;
    fetchTransactions(true);
  }

  // 重置过滤条件
  function resetFilters() {
    filters.search = '';
    filters.method = '';
    filters.statusCode = '';
    filters.dateRange = null;
  }

  // 获取过滤后的交易记录
  function getFilteredTransactions() {
    let filtered = [...transactions.value];

    // 搜索过滤
    if (filters.search) {
      const searchLower = filters.search.toLowerCase();
      filtered = filtered.filter(t => 
        t.request.url.toLowerCase().includes(searchLower) ||
        t.request.method.toLowerCase().includes(searchLower)
      );
    }

    // 方法过滤
    if (filters.method) {
      filtered = filtered.filter(t => t.request.method === filters.method);
    }

    // 状态码过滤
    if (filters.statusCode) {
      filtered = filtered.filter(t => 
        t.response?.statusCode.toString() === filters.statusCode
      );
    }

    // 日期范围过滤
    if (filters.dateRange) {
      const [start, end] = filters.dateRange;
      filtered = filtered.filter(t => 
        t.createdAt >= start && t.createdAt <= end
      );
    }

    return filtered;
  }

  // 计算属性：筛选后的交易记录
  const filteredTransactions = computed(() => getFilteredTransactions());

  // 计算属性：筛选后的记录数
  const filteredCount = computed(() => filteredTransactions.value.length);

  // 初始化WebSocket监听
  function initWebSocketListeners() {
    // 监听新的交易记录
    wsClient.on('transaction', (data: HttpTransaction) => {
      addTransaction(data);
    });

    // 监听交易记录更新
    wsClient.on('transaction_update', (data: HttpTransaction) => {
      updateTransaction(data);
    });

    // 监听记录清空事件
    wsClient.on('records_cleared', (data: { message: string }) => {
      console.log('📡 收到记录清空事件:', data.message);
      // 清空前端数据（不调用服务端API，避免重复）
      transactions.value = [];
      selectedTransaction.value = null;
      pagination.page = 1;
      pagination.total = 0;
    });

    // 监听连接状态变化
    wsClient.on('connection_status', (data: { status: string; attempts: number }) => {
      wsReconnectAttempts.value = data.attempts;
      
      switch (data.status) {
        case 'connected':
          wsConnected.value = true;
          wsReconnecting.value = false;
          console.log('WebSocket已连接');
          break;
        case 'disconnected':
          wsConnected.value = false;
          wsReconnecting.value = false;
          console.log('WebSocket已断开');
          break;
        case 'reconnecting':
          wsConnected.value = false;
          wsReconnecting.value = true;
          console.log(`WebSocket重连中... (${data.attempts}次)`);
          break;
        case 'failed':
          wsConnected.value = false;
          wsReconnecting.value = false;
          console.error('WebSocket连接失败，停止重连');
          break;
      }
    });

    // 尝试连接WebSocket
    connectWebSocket();
  }

  // 连接WebSocket
  async function connectWebSocket() {
    try {
      await wsClient.connect();
    } catch (error) {
      console.error('WebSocket连接失败:', error);
    }
  }

  // 强制重连WebSocket
  function forceReconnectWebSocket() {
    wsClient.forceReconnect();
  }

  // 清理WebSocket监听
  function cleanupWebSocketListeners() {
    wsClient.off('transaction', addTransaction);
    wsClient.off('transaction_update', updateTransaction);
    wsClient.off('records_cleared', () => {});
    wsClient.off('connection_status', () => {});
    wsClient.disconnect();
  }

  return {
    // 状态
    transactions,
    selectedTransaction,
    loading,
    error,
    pagination,
    filters,
    
    // WebSocket状态
    wsConnected,
    wsReconnecting,
    wsReconnectAttempts,
    
    // 计算属性
    filteredTransactions,
    filteredCount,
    
    // 方法
    fetchTransactions,
    fetchTransactionDetail,
    selectTransaction,
    addTransaction,
    updateTransaction,
    clearTransactions,
    applyFilters,
    resetFilters,
    getFilteredTransactions,
    initWebSocketListeners,
    cleanupWebSocketListeners,
    connectWebSocket,
    forceReconnectWebSocket,
    
    // IndexedDB 方法
    initDatabase,
    loadFromIndexedDB
  };
}); 